package com.amigo.online.provider.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.amigo.online.common.base.exception.IllegalParameterException;
import com.amigo.online.common.base.service.BaseService;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.dto.user.UserAraeDto;
import com.amigo.online.common.param.result.AreaInfo;
import com.amigo.online.common.param.result.UserAreaInfo;
import com.amigo.online.common.util.StringUtils;
import com.amigo.online.provider.common.mapper.AreaMapper;
import com.amigo.online.provider.common.model.entity.Area;
import com.amigo.online.provider.common.service.AreaService;
import com.amigo.online.provider.common.util.ConvertUtil;

@Service
@Transactional(rollbackFor = Exception.class)
public class AreaServiceImpl extends BaseService<Area> implements AreaService {

    @Resource
    private AreaMapper areaMapper;

    @Override
    public List<AreaInfo> getAreaListByPidAndLang(Integer pid, String lang) {
        if (pid == null || pid.intValue() < 0 || lang == null || StringUtils.isEmpty(lang)) {
            throw new IllegalParameterException(StatusCode.BAD_REQUEST);
        }
        List<Area> area_list = areaMapper.getAreaListByPid(pid);
        if (area_list == null) {
            return null;
        }
        List<AreaInfo> info_list = new ArrayList<AreaInfo>();
        for (Area area : area_list) {
            AreaInfo info = ConvertUtil.AreaToAreaInfo(area, lang);
            info_list.add(info);
        }
        return info_list;
    }

    @Override
    public AreaInfo getAreaByIdAndLang(Integer id, String lang) {
        if (id == null || id.intValue() <= 0 || lang == null || StringUtils.isEmpty(lang)) {
            throw new IllegalParameterException(StatusCode.BAD_REQUEST);
        }
        Area area = areaMapper.selectByPrimaryKey(id);
        AreaInfo info = ConvertUtil.AreaToAreaInfo(area, lang);
        return info;
    }

    @Override
    public UserAreaInfo getAreaInfo(UserAraeDto dto) {
        UserAreaInfo uai = new UserAreaInfo();
        AreaInfo a = this.getAreaByIdAndLang(dto.getCountry(), dto.getLang());
        if (a != null) {
            uai.setCountryName(a.getName());
        }
        AreaInfo b = this.getAreaByIdAndLang(dto.getPri(), dto.getLang());
        if (b != null) {
            uai.setProvinceName(b.getName());
        }
        AreaInfo c = this.getAreaByIdAndLang(dto.getCity(), dto.getLang());
        if (c != null) {
            uai.setCityName(c.getName());
        }
        return uai;
    }
}
